﻿using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using YYTea.MOdel.Model;
using YYTea.ORM;
using YYTea.Services.VModel;

namespace YYTea.Miljy.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        private readonly IConfiguration _configration;
        private readonly UserManager<UserInfo> _userManager;
        private readonly SignInManager<UserInfo> _signInManager;
        private readonly RoleManager<UserInfo> _roleManager;
        private readonly YYTeaContext _context;
        public AuthenticationController(
            IConfiguration configuration,
            UserManager<UserInfo> userManager,
            SignInManager<UserInfo> signInManager,
            RoleManager<UserInfo> roleManager,
            YYTeaContext context
            )
        {
            this._configration = configuration;
            this._userManager = userManager;
            this._signInManager = signInManager;
            this._roleManager = roleManager;
            this._context = context;
        }
        [HttpPost]
        public async Task<IActionResult> Login([FromBody] UserLogin login)
        {
            // 1.验证用户
            var loginResult = await _signInManager.PasswordSignInAsync(
                login.UserName,
                login.Password,
                //多次登录
                false,
                //是否锁定
                false
                );
            UserInfo userinfo = new UserInfo();
            if (login.UserName != userinfo.Email || login.UserName != userinfo.UserName && login.Password != userinfo.Password)
            {
                return BadRequest();
            }
            if (!loginResult.Succeeded)
            {
                return BadRequest();
            }
            var user = await _userManager.FindByNameAsync(login.UserName);

            // 2.创建jwt
            //herder
            var signitureAlgorithm = SecurityAlgorithms.HmacSha256;
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub,user.Email)
             };
            //获取用户角色
            var roleNames = await _userManager.GetRolesAsync(user);
            foreach (var roleName in roleNames)
            {
                var roleClaim = new Claim(ClaimTypes.Role, roleName);
                claims.Add(roleClaim);
            }
            //signiture
            var secreyByte = Encoding.UTF8.GetBytes(_configration["Authentication:SecreyKey"]);
            var secerykey = new SymmetricSecurityKey(secreyByte);
            var signingCredentials = new SigningCredentials(secerykey, signitureAlgorithm);

            var token = new JwtSecurityToken(
                issuer: _configration["Authentication:Issuer"],
                audience: _configration["Authentication:Audience"],
                claims,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddDays(1)
                );
            var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);

            return Ok(tokenStr);

        }
    }
}
